package Controller.Actions;

import Controller.*;
import Database.Document;
import DocumentSelector.DocumentSelector;
import EngineSelector.EngineSelector;
import Merger.Merger;
import Query.Dispatcher;
import Query.Priority;

import java.net.*;
import java.util.Vector;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class QueryAction implements Action {
    
    public QueryAction() {
    }
    
    public void perform(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        response.setContentType("text/html");
        response.setHeader("Cache-Control", "no-cache");
        
        String query = request.getParameter("query");
        String strN = request.getParameter("n");
        
        if(query == null || strN == null)
        {
            RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
            rd.forward(request, response);
        }
        
        int n = 0;
        try
        {
            n = Integer.parseInt(strN);
        }
        catch(Exception e)
        {
            RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
            rd.forward(request, response);            
        }
        
        doQuery(request, response, query, n);
    }
    
    public void doQuery(HttpServletRequest request, HttpServletResponse response, String query, int k)
    throws ServletException, IOException
    {
        EngineSelector e = new EngineSelector();
        Vector<Priority> priority = e.SelectEnginePriorities(query);
        
        DocumentSelector d = new DocumentSelector();
        Vector<Priority> proportion = d.GetDocumentProportion(priority, k);
        
        Dispatcher dis = new Dispatcher();
        Vector<Vector<Document>> resultset = dis.PerformQueries(query, 10);
        
        Merger m = new Merger();
        Vector<Document> result = m.DoMerge(resultset, proportion, k);
        
        request.setAttribute("list", result);
        RequestDispatcher rd = request.getRequestDispatcher("/query/resultquery.jsp");
        rd.forward(request, response);        
    }
}
